function [a,P] = Sarsa(P,S,mode)

global reward;      % immediate reward from state
global alpha;       % step-size constant
global delta;       % change
global epsilon;     % constant for epsilon-greedy selection
global gamma;       % discount rate
global lambda;      % eligibility trace value
global theta;       % parameters vector
global e;           % eligibility trace
global Fa;          % feature vector
global Qa;          % Q-value of current action

global random;      % counter of how many times an agent experimented
global total_reward;

memory = LoadMemory(P);
old_action = memory(2);

P_num = P{3};
F = Fa{P_num};

%'update eligibility trace'
for i = 1:numel(F) % update the eligibility trace
    index = F(i);
    e(P_num,index) = e(P_num,index) + 1;
end 

% subtract Qvalue for last action from reward
old_state_value = LoadValue(P);
current_state_value = GetReward(P,S,mode);
SaveValue(P,current_state_value);

reward =  current_state_value - old_state_value;
total_reward = total_reward + reward;

% if(P_num == 1)
% disp(sprintf('Player: %s, Reward: %s', num2str(P_num), num2str(reward)));
% end

Q = Qvalue(F, theta(P_num,:));
delta = reward - Q;

% select action epsilon-greedily
if(rand() < 1-epsilon)
    % select the maximizing action
    [a,P] = SelectActionFromPolicy(P,S,mode,theta);
else
    % select random action
    [a,P] = Random(P,S,mode);
    random = random + 1; % update random count for the team
end

% load the selected action
memory = LoadMemory(P);
action = memory(2);

% update Qa and Fa
Fa{P_num} = GetFeatures(P,S,mode, action);
Qa(P_num) = Qvalue(Fa{P_num}, theta(P_num,:));

% update parameter vector and eligibility trace
delta = delta + gamma*Qa(P_num);
theta(P_num,:) = theta(P_num,:) + alpha*delta*e(P_num,:);
e(P_num,:) = gamma*lambda*e(P_num,:);

% if(old_action == 1)
%     %disp(sprintf('Dribble update: %s', num2str(sum(alpha*delta*e(P_num,:)))));
%     disp(sprintf('Dribble update: %s Reward: %s New: %s Old: %s', num2str(delta), num2str(reward),num2str(current_state_value), num2str(old_state_value)));
% elseif(old_action > 1 && old_action <= 4 && old_action ~= 1+P{3})
%     %disp(sprintf('Pass update: %s', num2str(sum(alpha*delta*e(P_num,:)))));
%     disp(sprintf('Pass update: %s Reward: %s ', num2str(delta), num2str(reward)));
% elseif(old_action == 5)
%     disp(sprintf('GetOpen update: %s Reward: %s ', num2str(delta), num2str(reward)));    
% elseif(old_action == 6)
%     disp(sprintf('GoToBall update: %s Reward: %s ', num2str(delta), num2str(reward)));    
% end 

end